package cc.ttiot.thread.dataCollectionThread;

import cc.ttiot.mapper.dao.TemperatureAndHumidityMsgMapper;
import cc.ttiot.mapper.domain.TemperatureAndHumidityMsg;
import cc.ttiot.mapper.utils.MybatisUtils;
import cc.ttiot.service.dataCollection.io.impl.TemperatureAndHumidityCollection;
import cc.ttiot.utils.TimeUtils;
import org.apache.ibatis.session.SqlSession;

/**
 * @Description: TODO
 * @Author WangSuheng
 * @Date 2021/10/8 0:29
 * @Version 1.0
 */
public class TemperatureAndHumidityCollectThread implements Runnable {
    //数据库初始化
    /*
         1) SqlSession类是线程不安全的，所以每个线程都要有个单独的SqlSession
         2) 下面这种sqlSessionFactory.openSession()的方式获取SqlSession对象默认事务autoCommit设为false，
            所以除了查询语句其他语句执行后要调用sqlSession.commit()方法提交事务
    */
    private final SqlSession sqlSession = MybatisUtils.getSqlSession();
    private final TemperatureAndHumidityMsgMapper tahmMapper = sqlSession.getMapper(TemperatureAndHumidityMsgMapper.class);
    private final TemperatureAndHumidityMsg temperatureAndHumidityMsg = new TemperatureAndHumidityMsg();

    public TemperatureAndHumidityCollectThread() {
        super();
    }

    @Override
    public void run() {

        TemperatureAndHumidityCollection tahc = TemperatureAndHumidityCollection.getInstance();
        while (true) {
            short[] collect = null;
            try {
                collect = tahc.collect();
                if (collect != null) {
                    System.out.println("湿度为 : " + (double) collect[0] / 10);
                    System.out.println("温度为 : " + (double) collect[1] / 10);

                    //更新数据
                    temperatureAndHumidityMsg.setHumidity((float) collect[0] / 10);
                    temperatureAndHumidityMsg.setTemperature((float) collect[1] / 10);
                    temperatureAndHumidityMsg.setTime(TimeUtils.getMillisecondTime());

                    //存入数据库
                    tahmMapper.insertSingle(temperatureAndHumidityMsg);
                    sqlSession.commit();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
